<template>
<el-select
    :value="checks"
    :collapse-tags="true"
    @change="changeVal"
    multiple>
    <el-option
        v-for="item in data"
        :key="item.value"
        :label="item.label"
        :value="item.value">
        <span class="label">{{ item.label }}</span>
    </el-option>
</el-select>
</template>

<script>
export default {
    name: 'Seletion',
    props: {
        data: {
            type: Array
        },
        checks: [Array]
    },
    methods: {
        changeVal (checked) {
            // 获取选中的值
            const ischeck = checked.length > this.checks.length
            const current = ischeck ? this.diffArr(checked, this.checks) : this.diffArr(this.checks, checked)

            // 点击全选
            if (current[0] === '') {
                checked = ischeck ? this.data.map(item => item.value) : []
                return this.$emit('update:checks', checked)
            }
            // 点击全选以外的按钮
            if (ischeck) {
                if (checked.length === this.data.length - 1) {
                    checked.unshift('')
                }
            } else {
                const index = checked.findIndex(_ => _ === '')
                if (index > -1) {
                    checked.splice(index, 1)
                }
            }
            return this.$emit('update:checks', checked)
        },
        diffArr (arr, arr1) {
            return arr.filter(val => arr1.indexOf(val) < 0)
        }
    }
}
</script>

<style scoped lang="scss">
.label{
    margin-left: 8px;
}
</style>
